package mwa.cs.admin.ctrl;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import javazoom.upload.MultipartFormDataRequest;
import javazoom.upload.UploadBean;
import javazoom.upload.UploadException;
import javazoom.upload.UploadFile;
import mwa.cs.dao.GenDocDAO;
import mwa.cs.dao.PressReleaseDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.database.Database;
import mwa.cs.model.PressRelese;
import mwa.cs.util.JDate;

/**
 * Servlet implementation class CS82000Srvl
 */
public class CS82000Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Database db;
	public String vaNewImage ;
	public String vaDetailShow;
	public String vaTopicShow;
	public String vaTopicEdit;
	public String vaTopicDelete;
	private String vaAgentBrowser;
	private String vaUrlAddress;
	private int vnSiteId;
	private int vnUserId;
    /**
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS82000Srvl() {
        super();
       
    }
    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	// get site_id
    	vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
    	vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
    	vaUrlAddress = request.getParameter("url_address");
    	vaAgentBrowser = request.getParameter("agent_browser");
    	String vaProcessType = request.getParameter("vaProcessType");
		if(vaProcessType.equals("insert")){ 
			insert(request,response);	
		}else if (vaProcessType.equals("insert_upload")){
			insert_upload(request,response);	
		}else if(vaProcessType.equals("edit")){ 
			edit(request , response);
		}else if(vaProcessType.equals("delete")){
			delete(request,response);
		}else if(vaProcessType.equals("update")) {
			update(request,response);
		}else if (vaProcessType.equals("getDataTable")){
			getDataTable(request,response);
		}else if(vaProcessType.equals("update&upload")) {
			update_upload(request,response);
		}
    }
    
    public void insert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		
		this.db = new Database();
		String vaPin = request.getParameter("pin");
		String vaToPic = request.getParameter("topic");
		String vaDetail = request.getParameter("detail");
		String vaStartData = JDate.saveDate(request.getParameter("start_date"));
		String vaEndDate = JDate.saveDate(request.getParameter("end_date"));
		//run tomcat
		/*String vapin = new String(request.getParameter("pin").getBytes("ISO8859_1"), "UTF-8");
		String vatoPic = new String(request.getParameter("topic").getBytes("ISO8859_1"), "UTF-8");
		String vadetail = new String(request.getParameter("detail").getBytes("ISO8859_1"), "UTF-8");
		String vastartData = new String(JDate.saveDate(request.getParameter("start_date")).getBytes("ISO8859_1"), "UTF-8");
		String vaendDate = new String(JDate.saveDate(request.getParameter("end_date")).getBytes("ISO8859_1"), "UTF-8");*/
		
		String vaImageDefault ="news-thumb.jpg";
		PressRelese voPressRelese = new PressRelese();
		voPressRelese.setVnSiteId(vnSiteId);
		voPressRelese.setVaPin(vaPin);
		voPressRelese.setVaTopic(vaToPic);
		voPressRelese.setVaDetail(vaDetail);
		voPressRelese.setVaStartDate(vaStartData);
		voPressRelese.setVaEndDate(vaEndDate);
		voPressRelese.setVaImageUrl(vaImageDefault);
		voPressRelese.setVaType("P");
		voPressRelese.setVnInsertUserId(vnUserId);
		voPressRelese.setVaInsertDate(JDate.getDate());
		voPressRelese.setVaInsertTime(JDate.getTime());
		
		PressReleaseDAO voReleaseDAO = new PressReleaseDAO(db);
		try {
			db.beginTransaction();
			voReleaseDAO.addPressRelese(voPressRelese);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS82000", JDate.getDate(), JDate.getTime(),vnUserId, "CS82000Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		}
		response.getWriter().write("success insert");
		this.db.close();
    	
    }
    
    public void insert_upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		this.db = new Database();
		String vaPin = request.getParameter("pin");
		String vaToPic = request.getParameter("topic");
		String vaDetail = request.getParameter("detail");
		String vaStartData = JDate.saveDate(request.getParameter("start_date"));
		String vaEndDate = JDate.saveDate(request.getParameter("end_date"));
		
		//run tomcat
		/*String vapin = new String(request.getParameter("pin").getBytes("ISO8859_1"), "UTF-8");
		String vatoPic = new String(request.getParameter("topic").getBytes("ISO8859_1"), "UTF-8");
		String vadetail = new String(request.getParameter("detail").getBytes("ISO8859_1"), "UTF-8");
		String vastartData = new String(JDate.saveDate(request.getParameter("start_date")).getBytes("ISO8859_1"), "UTF-8");
		String vaendDate = new String(JDate.saveDate(request.getParameter("end_date")).getBytes("ISO8859_1"), "UTF-8");*/
		
		PressRelese voPressRelese = new PressRelese();
		voPressRelese.setVnSiteId(vnSiteId);
		voPressRelese.setVaPin(vaPin);
		voPressRelese.setVaTopic(vaToPic);
		voPressRelese.setVaDetail(vaDetail);
		voPressRelese.setVaStartDate(vaStartData);
		voPressRelese.setVaEndDate(vaEndDate);
		voPressRelese.setVaImageUrl(vaNewImage);
		voPressRelese.setVaType("P");
		voPressRelese.setVnInsertUserId(vnUserId);
		voPressRelese.setVaInsertDate(JDate.getDate());
		voPressRelese.setVaInsertTime(JDate.getTime());
		
		PressReleaseDAO voReleaseDAO = new PressReleaseDAO(db);
		try {
			db.beginTransaction();
			voReleaseDAO.addPressRelese(voPressRelese);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS82000", JDate.getDate(), JDate.getTime(),vnUserId, "CS82000Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		}
		response.getWriter().write("success insert_upload");
		this.db.close();
    	
    }
    
    public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		int  vnSiteId = 0;
		int  vnUserId;
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		
		this.db = new Database();
		String vaPin = request.getParameter("pin");
		String vaToPic = request.getParameter("topic");
		String vaDetail = request.getParameter("detail");
		String vaStartData = JDate.saveDate(request.getParameter("start_date"));
		String vaEndDate = JDate.saveDate(request.getParameter("end_date"));
		String vaOldTopic =request.getParameter("oldTopic");
		String vaOldNameImage = request.getParameter("oldNameImage");
		String vaOldStatDate = JDate.saveDate(request.getParameter("oldStartDate"));
		String vaOldEndDate =  JDate.saveDate(request.getParameter("oldEndDate"));
		//run tomcat
		/*String vapin = new String(request.getParameter("pin").getBytes("ISO8859_1"), "UTF-8");
		String vatoPic = new String(request.getParameter("topic").getBytes("ISO8859_1"), "UTF-8");
		String vadetail = new String(request.getParameter("detail").getBytes("ISO8859_1"), "UTF-8");
		String vastartData = new String(JDate.saveDate(request.getParameter("start_date")).getBytes("ISO8859_1"), "UTF-8");
		String vaendDate = new String(JDate.saveDate(request.getParameter("end_date")).getBytes("ISO8859_1"), "UTF-8");
		String vaoldTopic =new String (request.getParameter("oldTopic").getBytes("ISO8859_1"), "UTF-8");
		String vaoldNameImage = request.getParameter("oldNameImage");*/
		
		PressRelese voPressRelese = new PressRelese();
		voPressRelese.setVnSiteId(vnSiteId);
		voPressRelese.setVaPin(vaPin);
		voPressRelese.setVaTopic(vaToPic);
		voPressRelese.setVaDetail(vaDetail);
		voPressRelese.setVaStartDate(vaStartData);
		voPressRelese.setVaEndDate(vaEndDate);
		voPressRelese.setVaImageUrl(vaOldNameImage);
		voPressRelese.setVaType("P");
		voPressRelese.setVnUpdateUserId(vnUserId);
		voPressRelese.setVaUpdateDate(JDate.getDate());
		voPressRelese.setVaUpdateTime(JDate.getTime());
		
		PressReleaseDAO voReleaseDAO = new PressReleaseDAO(db);
		try {
			db.beginTransaction();
			voReleaseDAO.updatePressRelease(vnSiteId, vaOldTopic, vaOldStatDate, vaOldEndDate, voPressRelese);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS82000", JDate.getDate(), JDate.getTime(),vnUserId, "CS82000Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		}
		response.getWriter().write("update success");
		this.db.close();
    }
    
    
    public void update_upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		int  vnSiteId = 0;
		int  vnUserId;
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		
		this.db = new Database();
		String vaPin = request.getParameter("pin");
		String vaToPic = request.getParameter("topic");
		String vaDetail = request.getParameter("detail");
		String vaStartData = JDate.saveDate(request.getParameter("start_date"));
		String vaEndDate = JDate.saveDate(request.getParameter("end_date"));
		String vaOldTopic =request.getParameter("oldTopic");
		
		//run tomcat
		/*String vapin = new String(request.getParameter("pin").getBytes("ISO8859_1"), "UTF-8");
		String vatoPic = new String(request.getParameter("topic").getBytes("ISO8859_1"), "UTF-8");
		String vadetail = new String(request.getParameter("detail").getBytes("ISO8859_1"), "UTF-8");
		String vastartData = new String(JDate.saveDate(request.getParameter("start_date")).getBytes("ISO8859_1"), "UTF-8");
		String vaendDate = new String(JDate.saveDate(request.getParameter("end_date")).getBytes("ISO8859_1"), "UTF-8");
		String vaoldTopic = new String(request.getParameter("oldTopic").getBytes("ISO8859_1"), "UTF-8");*/
		
		PressRelese voPressRelese = new PressRelese();
		voPressRelese.setVnSiteId(vnSiteId);
		voPressRelese.setVaPin(vaPin);
		voPressRelese.setVaTopic(vaToPic);
		voPressRelese.setVaDetail(vaDetail);
		voPressRelese.setVaStartDate(vaStartData);
		voPressRelese.setVaEndDate(vaEndDate);
		voPressRelese.setVaImageUrl(vaNewImage);
		voPressRelese.setVaType("P");
		voPressRelese.setVnUpdateUserId(vnUserId);
		voPressRelese.setVaUpdateDate(JDate.getDate());
		voPressRelese.setVaUpdateTime(JDate.getTime());
		
		PressReleaseDAO voReleaseDAO = new PressReleaseDAO(db);
		try {
			db.beginTransaction();
			voReleaseDAO.updatePressRelease(vnSiteId, vaOldTopic, vaStartData, vaEndDate, voPressRelese);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS82000", JDate.getDate(), JDate.getTime(),vnUserId, "CS82000Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		}
		response.getWriter().write("update success");
		this.db.close();
    }
    

    public void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		this.db = new Database();
		int  vnSiteId= 0;
		String vaTopic = request.getParameter("topic");
		String vaStartData = JDate.saveDate(request.getParameter("start_date"));
		String vaEndDate = JDate.saveDate(request.getParameter("end_date"));
		String[] vaTopicArray = vaTopic.split("(\\...)");
	        for(int d=0; d<vaTopicArray.length; d++){
	        	vaTopicEdit= vaTopicArray[0];
	        }
	    JSONObject voJsonObject = new JSONObject();
    	PressReleaseDAO voReleaseDAO =new PressReleaseDAO(db);
    	Map<String, Object>  voMap = voReleaseDAO.findPressReleseByTopic(vnSiteId, vaTopicEdit, vaStartData, vaEndDate);
    	//System.voOut.println(voMap.get("TOPIC").toString());
    	voJsonObject.put("topic",voMap.get("TOPIC").toString());
    	voJsonObject.put("detail",voMap.get("DETAIL").toString());
    	voJsonObject.put("url",voMap.get("IMAGE_URL").toString());
    	response.getWriter().print(voJsonObject.toJSONString());
    	this.db.close();
    }
    
    
    public void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		int  vnUserId;
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		int  vnSiteId = 0;
		this.db = new Database();
		String vaTopic = request.getParameter("topic");
		String vaStartData = JDate.saveDate(request.getParameter("startDate"));
		String vaEndDate = JDate.saveDate(request.getParameter("endDate"));
		String vaNameImage = request.getParameter("url");
		//run tomcat
		/*String vatoPic = new String(request.getParameter("topic").getBytes("ISO8859_1"), "UTF-8");
		String vastartData = JDate.saveDate(request.getParameter("startDate"));
		String vaendDate = JDate.saveDate(request.getParameter("endDate"));
		String vanameImage = new String(request.getParameter("url").getBytes("ISO8859_1"),"UTF-8");*/
		String[] vaTopicArray = vaTopic.split("(\\...)");
        for(int d=0; d<vaTopicArray.length; d++){
        	vaTopicDelete= vaTopicArray[0];
        }
		PressReleaseDAO voReleaseDAO =  new PressReleaseDAO(db);
		try {
			db.beginTransaction();
			voReleaseDAO.deletePressReleseBySitId(vnSiteId,vaTopicDelete,vaStartData,vaEndDate);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS82000", JDate.getDate(), JDate.getTime(),vnUserId, "CS82000Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		}
		if(!vaNameImage.equals("news-thumb.jpg")){
			File voDeleteFile = new File(request.getRealPath("/")+"assets/images/new/"+vaNameImage);
			voDeleteFile.delete();
			response.getWriter().write("Success Delete");
		}
		this.db.close();
    }
    

    public void getDataTable(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter voOut = response.getWriter();
		this.db = new Database();
		PressReleaseDAO poDaoReleaseDAO = new PressReleaseDAO(db);
		List<Map<String , Object>> voListRelease;
		voListRelease = poDaoReleaseDAO.findPressReleaseBySiteIdAndTypeP();
		
		 String[] vaDetailArray = null; String[] vaTopicArray = null;
			for(int i=0 ;i<voListRelease.size();i++){
				Map<String , Object> voMapItem = (Map<String , Object>) voListRelease.get(i);
				voColumn = new JSONArray();
				voColumn.add(i+1);
				voColumn.add(voMapItem.get("PIN").toString());
				voColumn.add(voMapItem.get("IMAGE_URL").toString());
				//split for show 
				vaTopicArray = ((String) voMapItem.get("TOPIC")).split("(?<=\\G.{20})");
				for(int d=0; d<vaTopicArray.length; d++){
			            vaTopicShow = vaTopicArray[0]+"...";
			       }
				
				vaDetailArray = ((String) voMapItem.get("DETAIL")).split("(?<=\\G.{40})");
		        for(int d=0; d<vaDetailArray.length; d++){
		            vaDetailShow = vaDetailArray[0]+"...";
		        }
		        voColumn.add(vaTopicShow);
				voColumn.add(vaDetailShow);
				voColumn.add(JDate.showDate(voMapItem.get("START_DATE").toString()));
				voColumn.add(JDate.showDate(voMapItem.get("END_DATE").toString()));
				voRow.add(voColumn);
				
			}
			voObject.put("aaData", voRow);
			voOut.print(voObject.toJSONString());
			this.db.close();
	}
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String vaProcessType = request.getParameter("vaProcessType");
		
		if(vaProcessType != null && !vaProcessType.equals("")){ 
			processRequest(request,response);
		}else{
			MultipartFormDataRequest  voMul = null;
	    	 UploadBean voUp = new UploadBean();
	    			try {
	    				voMul = new MultipartFormDataRequest(request);
		    		    voUp.setFolderstore(request.getRealPath("/")+"assets/images/new");
		    		    voUp.setWhitelist("*.jpg,*.png,*.gif");
		    		    voUp.setOverwrite(true);
		    		    voUp.store(voMul,"fileImage");
		    			
		    			Hashtable voFiles = voMul.getFiles();
		    			UploadFile voFile = (UploadFile) voFiles.get("fileImage");
		    			String nameImage = voFile.getFileName();
		    			
		    			 File voTobeRenameFile = new File(request.getRealPath("/")+"assets/images/new/"+nameImage);
		    			 this.db = new Database();
			    		 GenDocDAO voDaoGenDocDAO = new GenDocDAO(db);
			    		 vaNewImage = "NEWS"+voDaoGenDocDAO.generatingNextMNDoc()+".jpg";
			    		 voTobeRenameFile.renameTo(new File(request.getRealPath("/")+"assets/images/new/"+vaNewImage));
		    			
					} catch (UploadException e) {
						e.printStackTrace();
					}
	    			this.db.close();
	    			
			}
	}

}
